package com.aiju.cash.ui.billing;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Discount;
import com.aiju.bean.DiscountType;
import com.aiju.bean.Good;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.DiscountApi;
import com.aiju.cash.receiver.MyReceiver;
import com.aiju.cash.ui.good.manager.GoodManager;
import com.aiju.cash.ui.member.MemberSearchActivity;
import com.aiju.cash.ui.member.entity.MemberCard;
import com.aiju.cash.ui.pay.PayMoneyActivity;
import com.aiju.cash.ui.pay.PayQRCodeActivity;
import com.aiju.cash.ui.pay.PaySuccessActivity;
import com.aiju.cash.ui.pay.PayZhiFBaoActivity;
import com.aiju.cash.ui.pay.entity.Detail;
import com.aiju.cash.ui.pay.entity.Pay;
import com.aiju.cash.ui.pay.manager.PayManager;
import com.aiju.cash.util.GsonHelper;
import com.aiju.cash.widgit.DiscountDialog;
import com.aiju.utils.L;
import com.aiju.utils.PreferencesUtils;
import com.aiju.utils.PriceUtil;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.aiju.utils.tts.BaiduTTSManager;
import com.aiju.widgit.dialog.OrderDialog;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 佐为
 * @date: 2016-12-14 15:39
 * @version: V1.0
 * @Description: 确认订单
 */
public class OrderActivity extends BaseTitleActivity implements View.OnClickListener {

    private List<Good> goods;
    private ListView mOrderListView;
    private TextView sumTextView, priceTextView, priceTextView1;
    private GoodManager goodManager;

    private View zkView, jjView;
    private TextView zkTextView, jjTextView;

    private TextView fTextView;
    private Discount mDiscount;

    private String memberPhone = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        setCenterTitle("确认订单");
        setRightTitle("选择优惠");

        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestDiscount();
            }
        });
        goodManager = GoodManager.getInstance(this);
        goods = goodManager.getSelectedGoodList();
        total = Double.valueOf(goodManager.getTotalPrice());   //应收

        sumTextView = (TextView) findViewById(R.id.tv_order_sum);
        priceTextView = (TextView) findViewById(R.id.tv_order_price);
        priceTextView1 = (TextView) findViewById(R.id.tv_shop_money);
        fTextView = (TextView) findViewById(R.id.tv_order_f);

        sumTextView.setText("" + goodManager.getTotalSum());
        priceTextView.setText("" + goodManager.getTotalPrice());
        priceTextView1.setText("" + goodManager.getTotalPrice());

        mOrderListView = (ListView) findViewById(R.id.lv_order);
        mOrderListView.setAdapter(new MyBaseAdapter(this, goods));
        findViewById(R.id.tv_order_pay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mDiscount != null && !checkDiscount(mDiscount)) {
                    T.ToastShort("所选优惠条件不适用");
                    return;
                }
                new OrderDialog(OrderActivity.this)
                        .setLayoutParams()
                        .setTotalPrice(PriceUtil.formatDouble(total))
                        .setListener(OrderActivity.this)
                        .show();
            }
        });

        //优惠券
        zkView = findViewById(R.id.rl_discount_zk);
        jjView = findViewById(R.id.rl_discount_jj);

        zkTextView = (TextView) findViewById(R.id.tv_discount_zk_name);
        jjTextView = (TextView) findViewById(R.id.tv_discount_jj_name);

        zkView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setVisibility(View.GONE);
                mDiscount = null;
                changePrice();
            }
        });
        jjView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setVisibility(View.GONE);
                mDiscount = null;
                changePrice();
            }
        });

        PayManager.PAY_FROM_TYPE = PayManager.FROM_ORDER;
        IntentFilter filter = new IntentFilter();
        filter.addAction(MyReceiver.MESSAGE_RECEIVED_ACTION);
        registerReceiver(myReceiver, filter);

        PayManager.setOrderFrom();
    }

    private void requestDiscount() {
        new DiscountApi(mDialogHelper).list(new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                List<DiscountType> discountTypes = GsonHelper.convertEntities(data, DiscountType.class);
                if (Util.isEmpty(discountTypes)) {
                    T.ToastShort("没有可选的优惠折扣");
                    return;
                }
                PreferencesUtils.putString(OrderActivity.this, "money", goodManager.getTotalPrice());
                new DiscountDialog(OrderActivity.this)
                        .setLayoutParams()
                        .setOnClickDiscount(new DiscountDialog.OnClickDiscount() {
                            @Override
                            public void onDiscount(Discount discount, String msg) {
                                discount.setName(msg.replace("\n", ""));
                                if (!checkDiscount(discount)) {
                                    T.ToastShort("所选优惠条件不适用");
                                    return;
                                }
                                mDiscount = discount;
                                findViewById(R.id.ly_favorable).setVisibility(View.VISIBLE);
                                findViewById(R.id.rl_order_f).setVisibility(View.VISIBLE);
                                findViewById(R.id.v_order_f).setVisibility(View.VISIBLE);
                                if (discount.getType() == 1) {
                                    zkView.setVisibility(View.VISIBLE);
                                    zkTextView.setText(msg);
                                    jjView.setVisibility(View.GONE);
                                } else {
                                    jjView.setVisibility(View.VISIBLE);
                                    jjTextView.setText(msg);
                                    zkView.setVisibility(View.GONE);
                                }
                                changePrice();

                            }

                            @Override
                            public void onCard(View view) {
                                selectMember();
                            }
                        })
                        .setDiscountList(discountTypes)
                        .show();

            }
        });
    }

    /**
     * 检查优惠券
     */
    private boolean checkDiscount(Discount discount) {
        Double total = Double.valueOf(goodManager.getTotalPrice());
        if (discount.getType() == 3 || discount.getType() == 4) {
            if (total < Double.valueOf(discount.getCondition())) {
                return false;
            }
        } else if (discount.getType() == 2) {
            if (total < Double.valueOf(discount.getValue())) {
                return false;
            }
        }
        return true;
    }

    /**
     * 选择会员
     */
    private void selectMember() {
        Intent intent = new Intent(this, MemberSearchActivity.class);
        intent.putExtra("type", MemberSearchActivity.SELECT_MEMVER);
        startActivityForResult(intent, 100);
    }

    private Double total = 0.00d;//应收
    private Double favorable = 0.00d;//优惠

    private void changePrice() {
        total = Double.valueOf(goodManager.getTotalPrice());
        if (mDiscount == null) {
            findViewById(R.id.ly_favorable).setVisibility(View.GONE);
            findViewById(R.id.rl_order_f).setVisibility(View.GONE);
            findViewById(R.id.v_order_f).setVisibility(View.GONE);
            fTextView.setText(PriceUtil.formatDouble(0d));
            priceTextView1.setText(PriceUtil.formatDouble(total));
            favorable = 0d;
        } else {
            if (mDiscount.getType() == 1 || mDiscount.getType() == 4) {
                double v = total * mDiscount.getDiscount();
                favorable = total - Double.valueOf(PriceUtil.formatDouble(v));
            } else {
                favorable = Double.valueOf(mDiscount.getValue());
            }
        }
        total -= favorable;

/*
        double v = Double.valueOf(goodManager.getTotalPrice()) - Double.valueOf(PriceUtil.formatDouble(total));*/
        fTextView.setText(PriceUtil.formatDouble(favorable));

        if (total < 0.00) {
            total = 0.00;
            priceTextView1.setText(PriceUtil.formatDouble(total));
            filter = true;
        } else {
            priceTextView1.setText(PriceUtil.formatDouble(total));
            filter = false;
        }
    }

    private boolean filter;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_pay_qr:
                if (!mUser.getShop().isWx() && !mUser.getShop().isAlipay()) {
                    T.ToastShort("您尚未签约任何三方支付，请联系客服");
                    return;
                }
                if (filter) {
                    T.ToastShort("应收金额为0元，请选择现金收款");
                    return;
                }
                Intent intent = new Intent(this, PayQRCodeActivity.class);
                intent.putExtra("price", PriceUtil.formatDouble(total));
                intent.putExtra("type", PayQRCodeActivity.SHOW_QR);
                startActivity(intent);
                break;
            case R.id.tv_pay_wechat:
                payName = "微信成功收款";
                if (!mUser.getShop().isWx()) {
                    T.ToastShort("您尚未签约微信支付，请联系客服");
                    return;
                }
                if (filter) {
                    T.ToastShort("应收金额为0元，请选择现金收款");
                    return;
                }
                startPayZhiFBaoActivity(1);
                break;
            case R.id.tv_pay_money:
                Intent moneyIntent = new Intent(this, PayMoneyActivity.class);
                Bundle moneyBundle = new Bundle();
                moneyBundle.putSerializable("pay", getPay());
                moneyIntent.putExtras(moneyBundle);
                startActivity(moneyIntent);
                break;
            case R.id.tv_pay_zhif:
                payName = "支付宝成功收款";
                if (filter) {
                    T.ToastShort("应收金额为0元，请选择现金收款");
                    return;
                }
                startPayZhiFBaoActivity(0);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(myReceiver);
        super.onDestroy();
    }

    /**
     * 后台推送
     */
    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String extras = intent.getStringExtra("extras");
            String massage = intent.getStringExtra("message");
            DataJson dataJson = null;
            try {
                JSONObject jsonObject = new JSONObject(extras);
                dataJson = new DataJson(jsonObject.getString("json"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (dataJson.isSuccess()) {
                String data = dataJson.getData().toString();
                if (data.equals("payment_0")) {
                    //starPaySussecc();
                } else if (data.equals("payment_1")) {
                    //starPaySussecc();
                } else if (data.equals("payment_2")) {
                    starPaySussecc(dataJson.getOther());
                } else if (data.equals("payment_3")) {
                    // starPaySussecc();
                } else if (data.equals("invite")) {
                    //T.ToastShort("邀请店员");
                } else if (data.equals("unbind")) {
                    //T.ToastShort("删除店员");
                }
            }
        }

    };
    private String payName;

    /**
     * 跳转支付成功
     *
     * @param serialNum
     */
    private void starPaySussecc(String serialNum) {
        L.d("Lifecycle", "payActivity");
        Intent intent = new Intent(OrderActivity.this, PaySuccessActivity.class);
        intent.putExtra("money", priceTextView1.getText().toString());

        intent.putExtra("serialNum", serialNum);
        PayManager.setOrderFrom();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                BaiduTTSManager.getInstance().speak(payName + priceTextView1.getText().toString() + "元");
            }
        });
        L.d("orderActivity 语音播报");
        L.d(payName + priceTextView1.getText().toString() + "元");

        startActivity(intent);
    }

    /**
     * 扫描支付
     *
     * @return
     */
    private void startPayZhiFBaoActivity(int type) {
        Intent zhifIntent = new Intent(this, PayZhiFBaoActivity.class);
        Bundle zhifBundle = new Bundle();
        zhifBundle.putSerializable("pay", getPay());
        zhifBundle.putInt("type", type);
        zhifIntent.putExtras(zhifBundle);
        startActivity(zhifIntent);
    }

    /**
     * 付款商品信息
     *
     * @return
     */
    private Pay getPay() {
        String price = PriceUtil.formatDouble(total);
        List<Detail> details = new ArrayList<>();
        for (Good good : goodManager.getSelectedGoodList()) {
            Detail detail = new Detail();
            detail.setGoodsId(good.getId());
            detail.setGoodsName(good.getName());
            if (good.isWeighGood()) {
                detail.setNum(String.valueOf(good.getWeigh()));
            } else {
                detail.setNum("" + goodManager.getSelectedItemCountById(good.getIntId()));
            }
            good.setSelectSum(goodManager.getSelectedItemCountById(good.getIntId()));
            detail.setPrice(good.getPrice());
            detail.setUnit(good.getUnit());
            detail.setSum(String.valueOf(good.getSelectSum() * Double.valueOf(good.getPrice())));

            detail.setImageUrl(good.getImageUrl());
            detail.setGoodsTypeId(good.getGoodsTypeId());
            detail.setGoodsTypeName(good.getGoodsTypeName());
            Double sum = 0d;
            if (good.isWeighGood()) {
                if (good.getUnit().equals("500克")) {
                    sum += Double.valueOf(good.getPrice()) * (Double.valueOf(good.getWeigh()) / 500);
                } else {
                    sum += Double.valueOf(good.getPrice()) * Double.valueOf(good.getWeigh());
                }
            } else {
                sum += Double.valueOf(good.getPrice()) * goodManager.getSelectedItemCountById(good.getIntId());
            }
            detail.setSum(PriceUtil.formatDouble(sum));

            if (!TextUtils.isEmpty(good.getCode())) {
                detail.setCode(good.getCode());
            }
            details.add(detail);
        }
        String detailString = new Gson().toJson(details);
        L.d("订单详细：" + detailString);

        Pay pay = new Pay();
        pay.setSelectGoods(goodManager.getSelectedGoodList());
        pay.setSum(goodManager.getTotalSum());
        pay.setStoreId(mUser.getShop().getStoreId());
        pay.setPrice(price);
        pay.setActualPrice(price);
        pay.setSumPrice(goodManager.getTotalPrice());
        pay.setOperatorId(mUser.getOperatorId());
        pay.setOperatorName(mUser.getUserName());
        pay.setSubject("向 " + mUser.getShop().getShopName() + " 付款");
        pay.setMemberPhone(memberPhone);
        pay.setShouldPrice(price);
        pay.setChangePrice("0");
        pay.setRoundPrice("0");

        double v = Double.valueOf(goodManager.getTotalPrice()) - Double.valueOf(price);
        pay.setPrivPrice(PriceUtil.formatDouble(favorable));
        if (mDiscount != null) {
            pay.setPrivType(mDiscount.getName());
        } else {
            pay.setPrivType("无");
        }
        pay.setDetail(detailString);
        return pay;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100) {
            if (null != data) {
                MemberCard memberCard = (MemberCard) data.getSerializableExtra("memberCard");

                if (memberCard != null) {
                    Discount discount = new Discount();
                    discount.setValue(memberCard.getDiscount());
                    if (!TextUtils.isEmpty(memberCard.getType()) && memberCard.getType().equals("3")) {
                        discount.setType(2);
                        zkView.setVisibility(View.VISIBLE);
                        zkTextView.setText("会员积分抵扣" + discount.getValue() + "元");
                        jjView.setVisibility(View.GONE);
                        discount.setName(zkTextView.getText().toString());
                    } else {
                        discount.setType(1);
                        jjView.setVisibility(View.VISIBLE);
                        jjTextView.setText("会员" + discount.getValue() + "折");
                        zkView.setVisibility(View.GONE);
                        discount.setName(jjTextView.getText().toString());
                    }
                    mDiscount = discount;
                    memberPhone = memberCard.getMemberPhone();
                    findViewById(R.id.ly_favorable).setVisibility(View.VISIBLE);
                    findViewById(R.id.rl_order_f).setVisibility(View.VISIBLE);
                    findViewById(R.id.v_order_f).setVisibility(View.VISIBLE);
                    changePrice();
                } else {
                    mDiscount = null;
                    jjView.setVisibility(View.GONE);
                    memberPhone = data.getStringExtra("memberPhone");
                    changePrice();
                }
            }
        }
    }

    private final class MyBaseAdapter extends BaseAdapter {

        private Context context;
        private List<Good> clerks;

        public MyBaseAdapter(Context context, List<Good> clerks) {
            this.context = context;
            this.clerks = clerks;
        }

        @Override
        public int getCount() {
            return clerks.size();
        }

        @Override
        public Object getItem(int position) {
            return clerks.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View rootView = LayoutInflater.from(context).inflate(R.layout.item_order, parent, false);

            TextView price = (TextView) rootView.findViewById(R.id.tv_order_price);
            TextView num = (TextView) rootView.findViewById(R.id.tv_order_num);
            TextView code = (TextView) rootView.findViewById(R.id.tv_order_code);
            TextView name = (TextView) rootView.findViewById(R.id.tv_order_name);

            Good good = clerks.get(position);
            if (good.isWeighGood()) {
                price.setText(good.getPrice() + "/" + good.getUnit());
                if (good.getUnit().equals("500克")) {
                    num.setText(String.valueOf(good.getWeigh() + "克"));
                } else {
                    num.setText(String.valueOf(good.getWeigh()) + good.getUnit());
                }
            } else {
                price.setText(good.getPrice());
                num.setText("x" + good.getSelectSum());
            }
            code.setText(good.getCode());
            name.setText(good.getName());
            return rootView;
        }
    }
}
